<template>
  <el-dialog v-model="visible" :title="form.id ? '修改' : '添加'" @closed="onReset" :close-on-click-modal="false">
    <el-form :model="form" ref="formRef" label-width="100px">
      <el-form-item label="计划名称">
        <el-input v-model="form.plan_name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="计划类型">
        <el-select v-model="form.plan_type" placeholder="请选择" clearable>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in planTypeOption"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划时间">
        <el-date-picker v-model="form.plan_time" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="任务类型">
        <el-select v-model="form.task_type" placeholder="请选择" clearable>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in taskTypeOption"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务性质">
        <el-select v-model="form.task_nature" placeholder="请选择" clearable>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in taskNatureOption"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报告时间">
        <el-date-picker v-model="form.report_time" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="计划报告名称">
        <el-input v-model="form.record_title" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="单位信息">
        <el-input v-model="form.unit_info" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="上传报告">
        <CustomUpload
          v-model="form.report_url"
          :limit="1"
          style="width: 100%"
          :show-file-list="true"
          :file-list="form.fileList"
        >
          <el-button type="primary">选择文件</el-button>
        </CustomUpload>
      </el-form-item>

      <el-form-item label="备案时间">
        <el-date-picker v-model="form.record_report_time" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="备案状态">
        <el-select v-model="form.record_report" placeholder="请选择" clearable>
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in recordReportOption"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目负责人">
        <el-input v-model="form.charge_name" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="证书">
        <el-upload
          v-model:file-list="imagesList"
          :action="upDataUrl + '/unit/upload/upload'"
          :headers="uploadHeader"
          list-type="picture-card"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :data="{ type: 'image' }"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="技术负责人">
        <el-input v-model="form.cto_name" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="证书">
        <el-upload
          v-model:file-list="imagesList2"
          :action="upDataUrl + '/unit/upload/upload'"
          :headers="uploadHeader"
          list-type="picture-card"
          :on-success="handleSuccess2"
          :on-preview="handlePictureCardPreview2"
          :on-remove="handleRemove2"
          :data="{ type: 'image' }"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { planTypeOption, taskTypeOption, taskNatureOption, recordReportOption } from '@/util/explain'
import { add } from '@/api/wbUnit'
import store from '@/store'
import { ElMessage } from 'element-plus'
import CustomUpload from '@/components/CustomUpload/index.vue'
const emit = defineEmits(['refresh'])
const visible = ref(false)
const formRef = ref()
const form = reactive({
  id: 0,
  plan_name: '',
  plan_type: '',
  plan_time: '',
  task_type: '',
  task_nature: '',
  report_time: '',
  record_title: '',
  record_report: '',
  record_report_time: '',
  report_url: '',
  unit_info: '',
  fileList: [],
  certificate: '',
  zs_image:'',
  imagesList: [],
  imagesList2: [],
  charge_name: '',
  cto_name: ''
})
const resetForm = JSON.parse(JSON.stringify(form))

const upDataUrl = ref(import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL)
const imagesList = ref<UploadUserFile[]>([])
const imagesList2 = ref<UploadUserFile[]>([])

const open = (data) => {
  visible.value = true
  imagesList.value = [];
  imagesList2.value = [];
  if (data) {
    form.fileList = [{ name: data.report_url, url: data.report_url }]
    let arr = data.certificate.split(',')
    imageList.value = data.certificate.split(',')
    if (data.certificate != '') {
      imagesList.value = arr.map((item: string) => {
        return {
          name: '',
          url: upDataUrl.value + item
        }
      })
    }

    let arr2 = data.zs_image.split(',')
    imageList2.value = data.zs_image.split(',')
    if (data.zs_image != '') {
      imagesList2.value = arr2.map((item: string) => {
        return {
          name: '',
          url: upDataUrl.value + item
        }
      })
    }

    Object.assign(form, data)
  }
}
const onConfirm = async () => {
  await formRef.value.validate()
  add(form).then(({ msg }: any) => {
    ElMessage.success(msg)
    visible.value = false
    emit('refresh')
  })
}
const onReset = () => {
  Object.keys(resetForm).forEach((item: string) => {
    form[item] = resetForm[item]
  })
}

import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'

const uploadHeader = computed(() => {
  return {
    'A-Token': store.state.user.a_token,
    'U-Token': store.state.user.u_token
  }
})

const imageList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const index = imageList.value.findIndex((item) => upDataUrl.value + item === uploadFile.url);
  imageList.value.splice(index, 1)
  form.certificate = imageList.value.join(',')
}

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  imageList.value.push(response.data.result)
  form.certificate = imageList.value.join(',')
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const imageList2 = ref([])
const dialogImageUrl2 = ref('')

const handleRemove2: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const index = imageList2.value.findIndex((item) => upDataUrl.value + item === uploadFile.url);
  imageList2.value.splice(index, 1)
  form.zs_image = imageList2.value.join(',')
}

const handleSuccess2: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  imageList2.value.push(response.data.result)
  form.zs_image = imageList2.value.join(',')
}

const handlePictureCardPreview2: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}


defineExpose({ open })
</script>

<style lang="scss" scoped></style>
